<template>
  <view class="content">
    <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
      width="100%" height="100%" viewBox="0 0 1600 900" preserveAspectRatio="xMidYMax slice">
      <defs>
        <linearGradient id="bg">
          <stop offset="0%" style="stop-color:rgba(130, 158, 249, 0.06)"></stop>
          <stop offset="50%" style="stop-color:rgba(76, 190, 255, 0.6)"></stop>
          <stop offset="100%" style="stop-color:rgba(115, 209, 72, 0.2)"></stop>
        </linearGradient>
        <path id="wave" fill="url(#bg)"
          d="M-363.852,502.589c0,0,236.988-41.997,505.475,0
          s371.981,38.998,575.971,0s293.985-39.278,505.474,5.859s493.475,48.368,716.963-4.995v560.106H-363.852V502.589z" />
      </defs>
      <g>
        <use xlink:href='#wave' opacity=".3">
          <animateTransform attributeName="transform" attributeType="XML" type="translate" dur="10s"
            calcMode="spline" values="270 230; -334 180; 270 230" keyTimes="0; .5; 1"
            keySplines="0.42, 0, 0.58, 1.0;0.42, 0, 0.58, 1.0" repeatCount="indefinite" />
        </use>
        <use xlink:href='#wave' opacity=".6">
          <animateTransform attributeName="transform" attributeType="XML" type="translate" dur="8s"
            calcMode="spline" values="-270 230;243 220;-270 230" keyTimes="0; .6; 1"
            keySplines="0.42, 0, 0.58, 1.0;0.42, 0, 0.58, 1.0" repeatCount="indefinite" />
        </use>
        <use xlink:href='#wave' opacty=".9">
          <animateTransform attributeName="transform" attributeType="XML" type="translate" dur="6s"
            calcMode="spline" values="0 230;-140 200;0 230" keyTimes="0; .4; 1"
            keySplines="0.42, 0, 0.58, 1.0;0.42, 0, 0.58, 1.0" repeatCount="indefinite" />
        </use>
      </g>
    </svg>
    
    <view class="loginBox">
      <h3 style="text-align: center;margin-bottom:120rpx;">Fast Emby</h3>
      <view class="inputBox">
		<uni-forms ref="baseForm" :model="user" :rules="rules">
			<uni-forms-item name="serverip">
				<view class="ipt">
				  <uni-icons type="pyq" size="24" color="rgb(66,157,250)"></uni-icons>
				  <input type="text" v-model="user.serverip" value="" placeholder="请输入服务"/>
				</view>
			</uni-forms-item>
			<uni-forms-item name="serverport">
				<view class="ipt">
				  <uni-icons type="pyq" size="24" color="rgb(66,157,250)"></uni-icons>
				  <input type="number" v-model="user.serverport" value="" placeholder="请输入端口"/>
				</view>
			</uni-forms-item>
			<uni-forms-item name="username">
				<view class="ipt">
				  <uni-icons type="contact" size="24" color="rgb(66,157,250)"></uni-icons>
				  <input type="text" v-model="user.username" value="" placeholder="请输入账号"/>
				</view>
			</uni-forms-item>
			<uni-forms-item name="password">
				<view class="ipt">
				  <uni-icons type="eye" size="24" color="rgb(66,157,250)"></uni-icons>
				  <input type="passsword" v-model="user.password" value="" placeholder="请输入密码"/>
				</view>
			</uni-forms-item>
		</uni-forms>
        <button @click="submit('baseForm')">登录</button>
      </view>
    </view>
	<!-- 底部安全区域 -->
	<view class="safe-area-inset" :style="{ height: safeAreaHeight + 'px' }"></view>
  </view>
</template>

<script>
	import request from '@/common/request'
	import store from '@/store/index.js'

	export default {
		name: 'login',
		data() {
			return {
				user: {
					username: "",
					password: "",
					serverip: "",
					serverport: 8096,
					deviceName: "",
					deviceId: "",
					deviceVersion: "",
					userAvatar: "",
					userId: ""
				},
				rules: {
					username: {
						rules: [{
							required: true,
							errorMessage: 'The username cannot be empty'
						}]
					},
					serverip: {
						rules: [{
							required: true,
							errorMessage: 'The serverip cannot be empty'
						}]
					},
					serverport: {
						rules: [{
							required: true,
							errorMessage: 'The serverport cannot be empty'
						}]
					},
					password: {
						rules: [{
							required: true,
							errorMessage: 'The password cannot be empty'
						}]
					}
				},
				// 屏幕尺寸相关变量
				screenHeight: 0,
				safeAreaHeight: 0,

				// 加载状态控制
				isLoading: false
			}
		},
		onLoad() {
			const systemInfo = uni.getSystemInfoSync()
			this.screenHeight = systemInfo.windowHeight
			this.safeAreaHeight = systemInfo.safeAreaInsets.bottom || 0
		},
		methods: {
			async submit(ref) {
				// 显示加载提示
				uni.showLoading({
					title: '登录中...',
					mask: true // 防止背景点击
				})
				this.isLoading = true

				try {
					const deviceInfo = await this.getDeviceInfo()
					this.user.deviceName = deviceInfo.deviceName
					this.user.deviceId = deviceInfo.deviceId

					await this.$refs[ref].validate()

					store.commit('user', this.user)
					uni.setStorageSync('user', JSON.stringify(this.user))

					try {
						const systemInfo = await request.get('/emby/system/info/public')
						this.user.deviceVersion = systemInfo.Version
					} catch (error) {
						uni.showToast({
							title: '登录失败',
							icon: 'error',
						})
						throw error
					}

					store.commit('user', this.user)
					uni.setStorageSync('user', JSON.stringify(this.user))

					let loginParams = {
						"Username": this.user.username,
						"Pw": this.user.password
					}

					const userinfo = await request.post('/emby/Users/authenticatebyname', loginParams)
					const { AccessToken, User } = userinfo

					this.user.userId = User.Id
					let serverUrl = `${this.user.serverip}:${this.user.serverport}`
					if (!serverUrl.startsWith('http')) {
						serverUrl = `http://${serverUrl}`
					}
					let avatar = `${serverUrl}/emby/Users/${User.Id}/Images/Primary`
					this.user.avatar = avatar

					uni.showToast({
						title: '登录成功',
						icon: 'success',
					})

					store.commit('token', AccessToken)
					store.commit('user', this.user)

					uni.setStorageSync('token', AccessToken)
					uni.setStorageSync('user', JSON.stringify(this.user))

					uni.switchTab({
						url: '/pages/index/index'
					})
				} catch (err) {
					console.log('错误信息：' + JSON.stringify(err))
				} finally {
					// 无论成功失败都关闭加载提示
					uni.hideLoading()
					this.isLoading = false
				}
			},

			getDeviceInfo() {
				const systemInfo = uni.getSystemInfoSync();
				return {
					deviceName: (systemInfo.osName || "Chrome") +"  "+ (systemInfo.deviceModel || ""),
					deviceId: systemInfo.deviceId || 'f31212e4-5ed5-4613-a27f-01afc7d2ca15',
				}
			}
		},
		created() {
			let userTmp1 = uni.getStorageSync('user')
			if (userTmp1) {
				let userTmp = JSON.parse(userTmp1)
				this.user.username = userTmp.username
				this.user.password = userTmp.password
				this.user.serverip = userTmp.serverip
				this.user.serverport = userTmp.serverport
			}
		}
	}
</script>


<style scoped>
  svg {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height:40%;
    box-sizing: border-box;
    display: block;
    /* background-color: #ffffff; */
  }
  
  .loginBox{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-60%);
    width: 90%;
    border-radius: 20rpx;
    padding: 60rpx;
    box-sizing: border-box;
  }
  h3{
    /* color:rgb(66,157,250); */
    font-size: 40rpx;
    letter-spacing: 10rpx;
    margin-bottom: 40rpx;
  }
  .inputBox{
    color: #000;
  }
  .ipt{
    height: 86rpx;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    /* margin-bottom: 40rpx; */
    background-color: #f5f5f5;
    border-radius: 10rpx;
    padding-left: 10rpx;
  }
  .ipt input{
    margin-left: 20rpx;
    font-size: 28rpx;
	width: 100%;
  }
  .ipt input{
    margin-left: 20rpx;
  }
  .forgetPwd{
    margin-top: 30rpx;
    font-size: 26rpx;
    color: #b5b5b5;
    text-align: end;
    padding:0 10rpx;
    display: flex;
    justify-content: space-between;
  }
  button{
    margin-top: 20rpx;
    line-height: 85rpx;
    text-align: center;
    background: rgb(66,157,250);
    border-radius: 40rpx;
    color: #fff;
    margin-top: 40rpx;
  }
  
  .tip{
    text-align: center;
    font-size: 28rpx;
    position: fixed;
    bottom: 50rpx;
    left: 50%;
    transform: translate(-50%,-50%);
    color: #f4f4f4;
  }
  .tipbox {
    text-align: center;
    margin-top: 100rpx;
  }
  
  .otherUser {
    margin-top: 30rpx;
    display: flex;
    justify-content: center;
  }
  
  .txt {
    font-size: 28rpx;
    color: #cbcbcb;
  }
  
  .otherUser .uni-icons {
    margin-left: 20rpx;
  }
  .yzm{
    text-align: end;
    font-size: 24rpx;
    background: linear-gradient(to right,rgb(66,157,250),rgb(0, 170, 127));
    height: 60rpx;
    width: 150rpx;
    line-height: 60rpx;
    text-align: center;
    border-radius: 10rpx;
    color: #fff;
  }
</style>